/* components */
import { 
  SettingGPTViewHeader,
  SettingGPTViewContent,
  SettingGPTViewContentTitle,
  SettingGPTViewContentSubTitle,
} from "@gpt/components"
import Chart from "@gpt/views/home/chart"
import LogDialog from "@gpt/views/home/log-dialog"
import SettingGPTHomeViewRobotList from "@gpt/views/home/list"
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum"
/* hooks */
import { useSettingGPTRobotHome } from "@gpt/hooks"
/* vue */
import { defineComponent } from "vue"
/* scss */
import "@gpt/views/home/index.scss"
/* types */
import { SettingGPTServiceItem } from "@gpt/types"
/* util */
import platform from "@src/platform"
import { getRootWindowInitData } from "@src/util/window"
import { setClipboardData } from "@src/util/dom"
import { message } from "@src/util/message"
import { isFalsy } from "@src/util/type"

type LogDialogComponent = InstanceType<typeof LogDialog>
type ChartComponent = InstanceType<typeof Chart>

export default defineComponent({
  name: ComponentNameEnum.SettingGPTHomeView,
  props: {
    
  },
  setup(props, { emit }) {
    
    const { 
      initialize, 
      initChat,
      loading,
      gptSystemRobot,
      gptRobotAppList,
      countList,
      onUpdateRobotSettingShareHandler,
      fetchGptRobotAppAdd,
      onfetchGptRobotAppListHandler,
      onDelRobotAppServiceHandler,
    } = useSettingGPTRobotHome()
    
    return {
      initialize,
      initChat,
      loading,
      gptRobotAppList,
      gptSystemRobot,
      countList,
      onUpdateRobotSettingShareHandler,
      fetchGptRobotAppAdd,
      onDelRobotAppServiceHandler,
      onfetchGptRobotAppListHandler,
    }
  },
  data() {
    return {
      
    }
  },
  computed: {
    robotId(): string {
      return String(this.gptSystemRobot?.id as unknown as string || '')
    },
    title(): string {
      return '小宝AI'
    },
    subTitle(): string {
      return "Hello，我是您的企业专属智能助手，作为一个企业AI助手，<br> 我不仅具备强大的自然语言处理技术，还能深度理解企业的业务需求，<br> 能够帮助您提高工作效率，助力您的企业实现更大的商业价值。"
    },
    logTitle(): string {
      return '使用情况'
    },
    shareTitle() {
      return '小宝AI分享链接'
    },
    shareSubTitle() {
      return '小宝能生成链接，分享到外部使用，外部使用只支持大模型的常识问答和应用百科的回答'
    },
    shareUrl(): string {
      const id = this.gptSystemRobot?.id || ''
      const rootWindowInitData = getRootWindowInitData()
      const tenantId = rootWindowInitData?.user?.tenantId || ''
      const robotId = id
      const url = `/shb/home/setting/gpt/chat?tenantId=${tenantId}&robotId=${robotId}`
      const origin = window.location.origin
      const fullUrl = `${origin}${url}`
      return fullUrl
    },
    loginUser(): Record<string, any> {
      const rootWindowInitData = getRootWindowInitData()
      return rootWindowInitData.user || {}
    },
    loginUserAuth(): Record<string, any> {
      return this.loginUser?.auth || {}
    },
    isShowLog(): boolean {
      return Boolean(this.loginUserAuth?.XIAOBAO_GPT_VIEW)
    },
    isAllowEdit(): boolean {
      return Boolean(this.loginUserAuth?.XIAOBAO_GPT_EDIT)
    },
    isNotAllowEdit(): boolean {
      return isFalsy(this.isAllowEdit)
    },
    isOpenShare(): boolean {
      return Boolean(this.gptSystemRobot.setting?.share)
    },
    modelName(): string {
      return this.gptSystemRobot?.setting?.modelName || ''
    },
    attrs(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ],
      }
    },
    logDialogComponent(): LogDialogComponent {
      return this.$refs.LogDialog as LogDialogComponent
    },
    chartComponent(): ChartComponent {
      return this.$refs.Chart as ChartComponent
    }
  },
  watch: {
    
  },
  mounted() {
    this.initialize()
    this.addMessageListenerHandler()
  },
  beforeDestroy() {
    this.removeMessageListenerHandler()
  },
  methods: {
    addMessageListenerHandler() {
      window.addEventListener('message', this.onMessageHandler)
    },
    onMessageHandler(event: MessageEvent) {
      const { action } = event.data;
      if (action == 'shb.frame.activatedPage') {
        this.addPageActiveHandler();
      }
    },
    addPageActiveHandler() {
      this.chartComponent.rerender()
    },
    removeMessageListenerHandler() {
      window.removeEventListener('message', this.onMessageHandler)
    },
    descriptionButtonClickHandler() {
      platform.openLink('https://doc.shb.ltd/shb_xoqazk/eka8tf9wv8x43arx/xgs8aywpqgn7ymug.html')
    },
    copyHandler() {
      setClipboardData(this.shareUrl, () => {
        message.success('复制成功')
      })
    },
    onOpenLogDialogHandler() {
      this.logDialogComponent.openDialog()
    },
    onSwitchChangeHandler(value: boolean) {      
      this.onUpdateRobotSettingShareHandler(value)
    },
    renderSwitch() {
      return (
        <el-switch
          disabled={this.loading || this.isNotAllowEdit}
          value={this.isOpenShare}
          onChange={this.onSwitchChangeHandler}
        >
        </el-switch>
      )
    },
    /**
     * @description 渲染使用说明按钮
     */
    renderDescriptionButton() {
      return (
        <el-button
          type="plain-third"
          onClick={this.descriptionButtonClickHandler}
        >
          使用说明
        </el-button>
      )
    },
    /** 
     * @description 渲染日志使用情况
    */
    renderLogContent() {
      return (
        <SettingGPTViewContent
        >
          
          <div class="setting-gpt-home-view-log-content-header">
            
            <div class="setting-gpt-home-view-log-content-header-title">
              <SettingGPTViewContentTitle
                title={this.logTitle}
              >
              </SettingGPTViewContentTitle>
              <span class="setting-gpt-home-view-log-content-header-title-info">
                <i class="iconfont icon-info"></i>
                <span>
                  最近一个月AI回答问题的次数
                </span>
              </span>
            </div>
            
            {this.isShowLog && (
              <div 
                class="setting-gpt-home-view-log-content-header-button"
                onClick={this.onOpenLogDialogHandler}
              >
                查看日志
              </div>
            )}
            
          </div>
          
          <Chart
            value={this.countList}
            ref="Chart"
          >
          </Chart>
          
        </SettingGPTViewContent>
      )
    },
    /**
     * @description 渲染分享内容
    */
    renderShareContent() {
      return (
        <SettingGPTViewContent
        >
          
          <div class="setting-gpt-home-view-share-content-header">
            
            <SettingGPTViewContentTitle
              title={this.shareTitle}
            >
            </SettingGPTViewContentTitle>
            
            { this.renderSwitch() }
            
          </div>
          
          <SettingGPTViewContentSubTitle
            title={this.shareSubTitle}
            v-show={this.isOpenShare}
          >
          </SettingGPTViewContentSubTitle>
          
          <div 
            class="setting-gpt-home-view-share-content-main"
            v-show={this.isOpenShare}
          >
            
            <el-input
              disabled
              value={this.shareUrl}
            >
            </el-input>
            
            <el-button
              type="primary"
              onClick={this.copyHandler}
            >
              复制链接
            </el-button>
            
          </div>
          
        </SettingGPTViewContent>
      )
    },
    /**
     * @description 渲染机器人列表内容
     */
    renderRobotListContent() {
      return (
        <SettingGPTHomeViewRobotList>
        </SettingGPTHomeViewRobotList>
      )
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.SettingGPTHomeView} {...this.attrs}>
        
        <SettingGPTViewHeader
          title={this.title}
          subTitle={this.subTitle}
        >
          <div slot="button">
            {this.renderDescriptionButton()}
          </div>
        </SettingGPTViewHeader>
        
        { this.renderLogContent() }
        
        { this.renderRobotListContent() }
        
        <LogDialog ref="LogDialog">
        </LogDialog>
        
      </div>
    )
  }
})